﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Swift;
using UnityEngine.UI;
using Swift.Math;
using SCM;

public class StatisticsUI : UIBase
{
    public Text Money;
    public Text Suppliment;
    public Text Timer;
    public SysSettingUI SysSetting;
    public Text FPS;

    protected override void StartOnlyOneTime()
    {
        Room4Client.OnResourceChanged += ResourceChanged;
        Room4Client.OnFrameElapsed += OnFrameElapsed;
    }

    int SupplimentLimit = 0;
    private void ResourceChanged(int player, string type, Fix64 num)
    {
        if (player != GameCore.Instance.MePlayer)
            return;

        var numTxt = ((int)num).ToString();
        if (type == "Money")
            Money.text = numTxt;
        else if (type == "SupplimentLimit")
            SupplimentLimit = (int)num;
        else if (type == "Suppliment")
        {
            Suppliment.text = numTxt + "/" + SupplimentLimit.ToString();
            Suppliment.color = num >= SupplimentLimit ? Color.red : Color.green;
        }
    }

    void RefreshSuppliment()
    {
        var num = GameCore.Instance.GetMyResource("Suppliment");
        Suppliment.text = num.ToString() + "/" + SupplimentLimit.ToString();
        Suppliment.color = num >= SupplimentLimit ? Color.red : Color.green;
    }

    public void ResetAll()
    {
        var gc = GameCore.Instance;
        SupplimentLimit = (int)gc.GetMyResource("SupplimentLimit");
        Money.text = gc.GetMyResource("Money").ToString();
        RefreshSuppliment();
    }

    public void OnOpenSysSetting()
    {
        SysSetting.Show();
    }

    private void OnFrameElapsed(Room4Client room)
    {
        var frameLeft = Room.MaxFrameNum - room.FrameNo;
        TimeSpan dt;

        if (frameLeft < 1200) // 最后 2 分钟改为倒计时，并用红色提示
        {
            dt = TimeSpan.FromMilliseconds(frameLeft * Room.FrameInterval);
            Timer.color = Color.red;
        }
        else 
        {
            dt = TimeSpan.FromMilliseconds(room.FrameNo * Room.FrameInterval);
            Timer.color = Color.black;
        }

        Timer.text = dt.Minutes.ToString().PadLeft(2, '0') + ":" + dt.Seconds.ToString().PadLeft(2, '0');
    }

    List<float> last10FrameTimeElapsed = new List<float>();
    private void Update()
    {
        float dt = Time.deltaTime;
        last10FrameTimeElapsed.Add(dt);
        if (last10FrameTimeElapsed.Count > 10)
            last10FrameTimeElapsed.RemoveAt(0);

        var tt = 0.0f;
        foreach (var t in last10FrameTimeElapsed)
            tt += t;

        FPS.text = ((int)(10 / tt)).ToString();
    }
}
